import paramiko
import datetime
import os
import yaml
import zipfile

# hostname = "192.168.87.19"
# port = 22
# username = "root"
# password = "jovision123$"
# remotepath = "/opt/vi-cloud/log/vi-dossier/log.log"
# localpath = "D:\共享"

class Remote:
    def __init__(self, hostname, port, username, password):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(hostname=hostname, port=port, username=username, password=password)
        self.now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        with open(os.path.join(os.getcwd(), "keyvar.yaml"), 'r', encoding='utf-8') as f:
            self.yamldict = yaml.load(f, Loader=yaml.Loader)

    def makepackage(self):
        p = self.yamldict['rootpath']
        stdin, stdout, stderr = self.ssh.exec_command("zip -r /tmp/{}.zip {}".format(self.now, p[0]))
        if stderr.read():
            print("打包失败", stderr.read())
        else:
            print("打包完成")

    def downpackage(self, hostname, port, username, password, localpath):
        tran = paramiko.Transport((hostname, port))
        tran.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(tran)
        sftp.get(os.path.join('/tmp/', self.now + '.zip'), os.path.join(localpath, self.now + '.zip'))
        sftp.close()
        print("下载完成")

    def openpackage(self, localpath):
        with zipfile.ZipFile(os.path.join(localpath, self.now + '.zip')) as zf:
            zf.extractall(localpath)
        print("解压完成")

    def __del__(self):
        self.ssh.close()


# r = Remote(hostname, port, username, password)
# r.makepackage()
# r.downpackage(hostname, port, username, password, localpath)
# r.openpackage(localpath)
